package com.bjtu.boatmq.common;

import com.bjtu.boatmq.common.protocol.SourceDecoder;
import com.bjtu.boatmq.common.protocol.SourceEncoder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.util.UUID;

import com.bjtu.boatmq.common.protocol.PacketSource;


public class NettyServer {

    private final int port;
    private PacketSource packetSource;
    private ChannelHandlerContext channelHandlerContext;

    public NettyServer(int port) {
        this.port = port;
    }

    public void receive() throws Exception {
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        NioEventLoopGroup boos = new NioEventLoopGroup(1);
        NioEventLoopGroup worker = new NioEventLoopGroup();
        serverBootstrap
                .group(boos, worker)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    protected void initChannel(NioSocketChannel ch) {

                        ch.pipeline().addLast(new SourceDecoder());
                        ch.pipeline().addLast(new SourceEncoder());
                        ch.pipeline().addLast(new ServerHandler());


                        ch.pipeline().addLast(new SimpleChannelInboundHandler<PacketSource>() {
                            @Override
                            protected void channelRead0(ChannelHandlerContext ctx, PacketSource ps) {
                                //System.out.println(ps);
                                packetSource = ps;
                                channelHandlerContext = ctx;   
                            }
                        });
                    }
                })
                .bind(port);
    }
    public PacketSource GetpacketSource() {
    	return packetSource;
    }
    public ChannelHandlerContext Getchannal() {
    	return channelHandlerContext;
    }
    public static void main(String[] args) throws Exception {
        NettyServer ns = new NettyServer(8000);
        while(true){
            ns.receive();
            ChannelHandlerContext context=ns.Getchannal();
            PacketSource ps=ns.GetpacketSource();
            System.out.println(context);
            System.out.println(ps);
            Thread.sleep(2000);
        }
    }
}

